﻿using System.IO;
using System.Text.Json;

namespace VM.Start.Common.Helper
{
    /// <summary>
    /// 对象深拷贝
    /// </summary>
    public class CloneObject
    {
        /// <summary>
        /// 对象深拷贝
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns>内存地址不同，数据相同的对象</returns>
        public static T DeepCopy<T>(T obj)
        {
            if (obj == null)
                return default;

            using (var ms = new MemoryStream())
            {
                JsonSerializer.Serialize(ms, obj);
                ms.Position = 0;
                return JsonSerializer.Deserialize<T>(ms);
            }

        }

    }
}
